// import TableFilterMixin from '@/mixins/TableFilterMixin'
import { Component } from 'vue-facing-decorator'
import Render from '@/render/Render'
import toNative from '@/utils/toNative'
import { Button } from 'ant-design-vue'
import { RedoOutlined, DownloadOutlined } from '@ant-design/icons-vue'
import type { FormItemDto } from '@/components/low-code/types'
import {
    getInsuranceCompanyList,
    getLongInsuranceCount,
    getLongInsuranceCaseList,
    getPeriodInsuranceMaterials,
    exportPeriodInsuranceCaseList,
    getMaterialInsureCompany,
    getSaleList
} from '@/api/insurance/period/index'
import type {
    LongInsuranceCaseListDto,
    InsuraceSaleDto,
    InsuraceeCompanyListDto,
    InsuranceCountDto,
    LongInsuranceCaseDto,
    ReportCaseResultDto,
    PeriodInsuranceMaterialsDto,
    InsuranceMaterialsFileDto
} from '@/api/insurance/period/types'
import TableRender, { type TableRenderColumnTypes } from '@/render/TableRender'
import { type VxeGridPropTypes, type VxeTableDataRow, type VxeColumnSlotTypes } from 'vxe-table'
import TableDetail from '../components/TableDetail'
import SetInfoPop from '../components/SetInfoPop'
import SetMaterialPop from '../components/SetMaterial'
import AddClaimsPop from '../components/AddClaimsPop'
import { ref, computed } from 'vue'
import { downloadFile, getCompanyListByName } from '@/utils/util'
import userStore from '@/stores/user'
import { ClaimPeriodStatusCnEnum, getKeyToEnum, HurtStatusCnEnum, MaterialStatusCnEnum } from '@/const/enum'
import DrawerDetail from '../components/DrawerDetail'
import type { FilterDto } from '@/render/FilterRender'

@Component
export class LongInsuranceView extends TableRender {
    insureCompanyList = [] as string[]
    showAddClaims = false
    insuranceMaterialInfo = {} as LongInsuranceCaseListDto<ReportCaseResultDto>
    showSetInfo = false
    insuranceBasicInfo = {} as LongInsuranceCaseListDto<ReportCaseResultDto>
    showSetMaterialInfo = false
    isDelState = true
    noFilterPadding = true
    longInsuranceCount = {} as InsuranceCountDto
    previewList = [] as PeriodInsuranceMaterialsDto<InsuranceMaterialsFileDto>[]

    showDrawerDetail = false

    insureData = [
        { title: '案件总数', key: 'totalReportCaseCount' },
        { title: '待理赔', key: 'totalClaimsPendingCount' },
        { title: '已确认金额', key: 'totalNotarizePriceCount' },
        { title: '已结案', key: 'totalSettleLawsuitCount' },
        { title: '撤案/驳回', key: 'totalRejectCount' },
        { title: '已理赔金额', key: 'totalFinalMoney' },
        { title: '预估金额', key: 'totalEstimateMoney' }
    ] as { title: string; key: string }[]
    // insuranceStateObj = {
    //     0: { label: '待处理', value: 0, color: 'text-yellow' },
    //     1: { label: '处理中', value: 1, color: 'text-blue-light-100' },
    //     2: { label: '已结案', value: 2, color: 'text-green' },
    //     3: { label: '已驳回', value: 3, color: 'text-red' },
    //     4: { label: '已撤销', value: 4, color: 'text-black-300' },
    //     5: { label: '已确认金额', value: 5, color: 'text-blue' },
    //     6: { label: '保险垫付', value: 6, color: 'text-blue' }
    // } as { [key: number]: { label: string; value: number; color: string } }

    filterConfig() {
        return {
            companyName: {
                name: '客户名称',
                element: 'autoComplete',
                class: 'w-full',
                placeholder: '请输入后选择',
                optionsType: 'company'
            },
            insurCompany: {
                name: '保司名称',
                element: 'select',
                value: '',
                options: [],
                params: {
                    method: async (event: string) => {
                        if (event) {
                            console.log(event, '获取保司列表')
                        }
                    }
                }
            },
            salesId: {
                name: '所属商务',
                element: 'select',
                placeholder: '请输入后选择',
                remote: true,
                options: [],
                params: {
                    method: async (event: string) => {
                        if (event) {
                            const res = await getSaleList({ isSelectSale: 1, salesName: event })
                            this.filters.salesId.options = res.map(item => ({
                                label: item.saleName,
                                value: item.saleId
                            })
                            )
                        }
                    }
                }
            },
            outDangerUserName: {
                name: '出险人姓名',
                element: 'input'
            },
            serveCompanyId: {
                name: '派遣单位',
                element: 'select',
                placeholder: '请输入后选择',
                optionsType: 'serveCompany'
            },
            outDangerIdCardNo: {
                name: '出险人身份证',
                element: 'input'
            },
            outDangerPhone: {
                name: '出险人手机号',
                element: 'input'
            },
            reportPhone: {
                name: '报案人手机号',
                element: 'input'
            },
            reportStatus: {
                name: '处理状态',
                element: 'select',
                options: getKeyToEnum(ClaimPeriodStatusCnEnum)
            },
            uploadStatus: {
                name: '材料状态',
                element: 'select',
                options: getKeyToEnum(MaterialStatusCnEnum, true)
            },
            hurtStatus: {
                name: '是否骨折',
                element: 'select',
                options: getKeyToEnum(HurtStatusCnEnum)
            },
            dateRange: {
                name: '出险日期',
                element: 'datetime',
                type: 'daterange',
                value: '',
                params: {
                    valueFormat: 'YYYY-MM-DD'
                }
            },
            // search: {
            //     name: '搜索',
            //     element: 'button',
            //     span: 1,
            //     class: 'relative',
            //     callback: {
            //         click: () => {
            //             console.log(this.getFilters(), 'huoqu1jguo1')
            //         }
            //     }
            // },
            // clear: {
            //     name: (
            //         <div class="ml-8 text-black-light-200 flex items-center">
            //             <div class="mr-4">
            //                 <RedoOutlined style="fontSize:16px" />
            //             </div>
            //             清空条件
            //         </div>
            //     ),
            //     element: 'button',
            //     params: {
            //         text: true
            //     },
            //     span: 2,
            //     callback: {
            //         click: () => {
            //             console.log('点击了')
            //         }
            //     }
            // }
        } as FilterDto
    }

    tableColumnConfigOld = () =>
        [
            {
                title: '操作',
                width: 50,
                params: {
                    buttons: [
                        {
                            text: '设置',
                            event: (row) => this.onOpenSetInfo(row)
                        },
                        // {
                        //     text: '材料',
                        //     hidden: (row) => !this.canShowAdd(row.insurCompany),
                        //     event: (row) => this.onOpenSetMaterialInfo(row)
                        // }
                    ]
                },
                slots: {
                    default: 'tooltipButtons'
                }
            },
            {
                field: 'companyName',
                title: '客户名称',
                width: 200,
                params: {
                    event: (row: LongInsuranceCaseListDto<ReportCaseResultDto>) => {
                        this.handleShowDetal(row)
                        // this.insuranceBasicInfo = row
                        // this.showDrawerDetail = true
                    }
                },
                slots: {
                    default: 'clickable'
                }
            },
            {
                field: 'outDangerUserName',
                title: '出险人姓名'
            },
            {
                field: 'reportStatus',
                title: '处理状态',
                formatter: ({ row }) => {
                    return ClaimPeriodStatusCnEnum[row.reportStatus]
                },
                params: {
                    colors: {
                        0: 'blue-200',
                        1: 'yellow',
                        2: 'green',
                        3: 'red',
                        4: 'black-300',
                        5: 'cyan',
                        6: 'cyan'
                    }
                },
                slots: {
                    default: 'status'
                }
            },
            {
                field: 'serveCompanyName',
                title: '被派遣单位',
                width: 200
            },
            {
                field: 'insurCompanyName',
                title: '承保公司'
            },
            {
                title: '可用工种',
                width: 200,
                formatter: ({ row }) => {
                    return row.occupationName
                        ? row.occupationName + '（' + row.occupationLevel + '类）'
                        : '--'
                }
            },
            {
                field: 'estimateMoney',
                title: '预估金额'
            },
            {
                field: 'finalMoney',
                title: '最终金额'
            },
            {
                field: 'salesName',
                title: '所属业务员'
            },
            {
                field: 'createTime',
                title: '录入时间',
                width: 160
            }
        ] as TableRenderColumnTypes<LongInsuranceCaseListDto<ReportCaseResultDto>>

    handleShowDetal(row: LongInsuranceCaseListDto<ReportCaseResultDto>) {
        this.insuranceBasicInfo = row
        this.showDrawerDetail = true
    }

    onDeleteProgress() {
        this.reloadPage()
    }

    // 打开新增报案弹窗
    onOpenAddClaims() {
        this.showAddClaims = true
    }

    canShowAdd(companyCode: string) {
        return this.insureCompanyList.some((i: string) => i === companyCode)
    }
    hasPermission(prem: string) {
        const user = userStore()
        return user.permissions.some((i: string) => i === prem)
    }

    // 导出报案列表
    async onExportPeriodInsuranceCaseList() {
        const data = this.getFilters() as LongInsuranceCaseDto
        console.log(data, 'datadata')
        if (data.dateRange) {
            data.outDangerStartDate = data.dateRange[0] || ''
            data.outDangerEndDate = data.dateRange[1] || ''
            data.dateRange = undefined
        }
        const url = await exportPeriodInsuranceCaseList(data)
        downloadFile(url)
        console.log(url, 'urlurl')
    }
    // 打开设置弹窗并且存储row数据
    onOpenSetInfo(data: LongInsuranceCaseListDto<ReportCaseResultDto>) {
        this.insuranceBasicInfo = data
        this.showSetInfo = true
    }
    // 打开设置材料弹窗
    async onOpenSetMaterialInfo(event: LongInsuranceCaseListDto<ReportCaseResultDto>) {
        // 获取理赔材料列表
        this.insuranceMaterialInfo = event
        await this.initPeriodInsuranceMaterials()
        this.showSetMaterialInfo = true
    }
    // 获取理赔材料列表
    async initPeriodInsuranceMaterials() {
        const result = await getPeriodInsuranceMaterials({
            reportCaseId: Number(this.insuranceMaterialInfo.id),
            insureCompany: this.insuranceMaterialInfo.insurCompany
        })
        this.previewList = result
        console.log(result, 'resultresultresult')
        return
    }

    // 获取保司列表
    async initInsuranceCompanyList() {
        const result = await getInsuranceCompanyList()
        this.filters.insurCompany.options = result.map((item: InsuraceeCompanyListDto) => {
            return {
                label: item.dictLabel,
                value: item.dictValue
            }
        })
    }
    // 获取长期保险统计
    async initLongInsuranceCount() {
        const result = await getLongInsuranceCount()
        this.longInsuranceCount = result
    }

    async created() {
        this.insureCompanyList = await getMaterialInsureCompany()
        console.log(this.insureCompanyList, 'resultdhsal1')
        this.initLongInsuranceCount()
        this.initInsuranceCompanyList()
    }
    onLoadData(page: number, size: number, filters: LongInsuranceCaseDto) {
        console.log(filters, 'filtersfilters')
        if (filters.dateRange) {
            filters.outDangerStartDate = filters.dateRange[0] || ''
            filters.outDangerEndDate = filters.dateRange[1] || ''
            filters.dateRange = undefined
        }
        return getLongInsuranceCaseList({
            pageNum: page,
            pageSize: size,
            ...filters
        })
    }

    renderRightBtns() {
        return (
            <div class="flex flex-row-reverse mt-4">
                <Button icon={<DownloadOutlined />} type="text" onClick={this.onOpenAddClaims}>
                    新增报案
                </Button>
                <Button
                    icon={<DownloadOutlined />}
                    type="text"
                    onClick={this.onExportPeriodInsuranceCaseList}
                >
                    导出
                </Button>
            </div>
        )
    }

    renderInsureData() {
        return (
            <div>
                <div class="flex items-center justify-between gap-6 my-12">
                    {this.insureData.map((item: { title: string; key: string }) => {
                        return (
                            <div class="flex-1 flex flex-col items-center pb-8">
                                <div class="text-base">{item.title}</div>
                                <div class="font-bold text-xl text-black-100">
                                    {this.longInsuranceCount[item.key]}
                                </div>
                            </div>
                        )
                    })}
                </div>
            </div>
        )
    }

    render() {
        return (
            <div class="flex flex-col h-full overflow-hidden px-20px">
                {this.renderInsureData()}
                {super.render()}
                {
                    <DrawerDetail
                        v-model:show={this.showDrawerDetail}
                        claimData={this.insuranceBasicInfo}
                        type="period"
                    />
                }
                {
                    <SetInfoPop
                        v-model:show={this.showSetInfo}
                        basicInfo={this.insuranceBasicInfo}
                        onRefresh={this.reloadPage}
                        type="period"
                    />
                }
                {/* {
                    <SetMaterialPop
                        v-model:show={this.showSetMaterialInfo}
                        previewList={this.previewList}
                        basicInfo={this.insuranceMaterialInfo}
                        type="period"
                        onChange={this.initPeriodInsuranceMaterials}
                    />
                } */}
                {<AddClaimsPop v-model:show={this.showAddClaims} onChange={this.reloadPage} />}
            </div>
        )
    }
}

export default toNative<{}, {}>(LongInsuranceView)
